package cn.jbit.smbms.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.jbit.smbms.Util.AjaxResult;
import cn.jbit.smbms.Util.CommentData;
import cn.jbit.smbms.Util.Pager;
import cn.jbit.smbms.pojo.Bill;
import cn.jbit.smbms.pojo.Provider;
import cn.jbit.smbms.pojo.User;
import cn.jbit.smbms.service.ProviderService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/provider")
@Controller
public class ProviderController {
    @Autowired
    private ProviderService providerService;

    @RequestMapping("/list")
    public String list() {
        return "provider/list";
    }
    @RequestMapping("/add")
    public String add() {
        return "provider/add";
    }
    @RequestMapping("/modify")
    public String modify(Integer id,Map<String,Object>map) {
        try {
            Provider provider = providerService.queryProviderView(id);
            if (provider != null) {
                map.put("provider",provider);
            }else{
                throw new RuntimeException("显示供应商信息出错！");
            }
        } catch (Exception e) {
            map.put("message",e.getMessage());
            e.printStackTrace();
        }
        return "provider/modify";
    }

    @ResponseBody
    @RequestMapping("/domodify")
    public Object domodify(Provider provider,Map<String,Object>map,HttpSession session){
        AjaxResult result=new AjaxResult();
        try {
            User loginUser=(User) session.getAttribute(CommentData.LOGIN_SESSION);
            provider.setModifyBy(loginUser.getId());
            provider.setModifyDate(new Date());
            map.put("provider",provider);
            int count=providerService.updateProvider(provider);
            result.setSuccess(count==1);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping("doadd")
    public String doadd(Provider provider, @RequestParam("licPic") MultipartFile multipartFile, HttpSession session,Map<String,Object>map){
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String ext=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= UUID.randomUUID().toString();
            String separator=File.separator;
            String localPath="F:"+separator+"upload"+separator;
            if (!new File(localPath).exists()){
                new File(localPath).mkdir();
            }
            //String localPath="/usr/temp/";//linux路径
            String path=localPath+newFileName+ext;
            String picPath=newFileName+ext;
            File file=new File(path);
            User loginUser=(User)session.getAttribute(CommentData.LOGIN_SESSION);
            provider.setCreatedBy(loginUser.getId());
            provider.setCreationDate(new Date());
            provider.setLicPicPath(picPath);
            int count=providerService.addProvider(provider);
            if (count==1){
                multipartFile.transferTo(file);
                return "redirect:/provider/list";
            }else{
                map.put("provider",provider);
                throw new RuntimeException("新增供应商出现异常！");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "provider/add";
    }
    @ResponseBody
    @RequestMapping("/dolist")
    public Object dolist(Integer pageIndex,Integer pageSize,
                String proCode,String proName,Map<String,Object>param) {
        AjaxResult result = new AjaxResult();
        Pager<Provider> pager=new Pager<>();
        try {
            param.put("pageIndex",pageIndex);
            param.put("pageSize",pageSize);
            pager.setPageSize(pageSize);
            pager.setPageIndex(pageIndex);
            param.put("pageForm",(pageIndex-1)*pageSize);
            param.put("proCode",proCode);
            param.put("proName",proName);
            //1-根据条件查询总记录条数
            int count=providerService.queryListCount(param);
            pager.setTotalCount(count);
            //2-根据条件查询provider的集合
            List<Provider> providers=providerService.queryListByParam(param);
            pager.setList(providers);
            result.setParam(param);
            result.setPage(pager);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(Integer id){
        AjaxResult result=new AjaxResult();
        try {
            Provider provider = providerService.queryProviderView(id);
            String licPicPath = provider.getLicPicPath();
            String separator=File.separator;
            String realPath="F:"+separator+"upload"+separator;
            File oldFile=new File(realPath+licPicPath);
            if (oldFile.exists()) {
                oldFile.delete();
            }
            int count=providerService.deleteById(id);
            result.setSuccess(count==1);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }

        return result;
    }
    @RequestMapping("view")
    public String view(Integer id,Map<String,Object>param){
        try {
            Provider provider=providerService.queryProviderView(id);
            if (provider != null) {
                param.put("provider",provider);
            }else{
                throw new RuntimeException("查询为空异常！");
            }
        } catch (Exception e) {
            param.put("message",e.getMessage());
            e.printStackTrace();
        }
        return"provider/view";
    }
    @ResponseBody
    @RequestMapping("/downloadExcel")
    public Object downloadExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response){
        AjaxResult result=new AjaxResult();
        List<Provider> providerlist=null;
        try {
            providerlist = providerService.providerlist();
            if (providerlist != null) {
                ExportParams params=new ExportParams("供应商信息表","sheet1", ExcelType.XSSF);
                map.put(NormalExcelConstants.DATA_LIST,providerlist);
                map.put(NormalExcelConstants.CLASS,Provider.class);
                map.put(NormalExcelConstants.PARAMS,params);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                map.put(NormalExcelConstants.FILE_NAME,"供应商信息表"+sdf.format(new Date()));
                PoiBaseView.render(map,request,response,NormalExcelConstants.EASYPOI_EXCEL_VIEW);
                result.setSuccess(true);
            }else{
                result.setMessage("查询失败！");
                result.setSuccess(false);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            e.printStackTrace();
        }
        return result;
    }


}
